import { getUserInfoAPI, loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  state: {
    token: getToken(), // 初始化的时候从本地缓存读取
    userInfo: {} // 存储用户信息
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 同步到持久化
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      // 删除本地缓存的token
      removeToken()
    },
    setUserInfo(state, preload) {
      state.userInfo = preload // 更新mutations
    }
  },
  actions: {
    // store是框架层传入的
    async login(store, data) {
      const token = await loginAPI(data)
      store.commit('setToken', token)
    },
    async getUserInfo(store) {
      store.commit('setUserInfo', await getUserInfoAPI())
    },
    loginout(store) {
      store.commit('removeToken')
      store.commit('setUserInfo', {})
    }
  },
  namespaced: true // 命名空间
}
